<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 *
 * Date: 2016/11/19
 * Time: 23:41
 */

namespace base;


class Redis
{
    /**
     * @var Redis
     */
    private static $_instance = null;

    /**
     * redis默认配置
     * @var array
     */
    private static $config = [
        'host'       => '127.0.0.1', // redis主机
        'port'       => 6379, // redis端口
        'password'   => '', // 密码
        'select'     => 0, // 操作库
        'expire'     => 3600, // 有效期(秒)
        'timeout'    => 0, // 超时时间(秒)
        'persistent' => true, // 是否长连接
    ];

    /**
     * 构造函数
     * Redis constructor.
     */
    private function __construct()
    {

    }

    /**
     * 克隆
     */
    private function __clone()
    {

    }

    /**
     * 获取redis连接实例
     * @param array $config 配置
     * @return Redis|\Redis 返回redis连接实例
     */
    public static function getInstance($config = [])
    {
        if (!extension_loaded('redis')) {
            throw new \BadFunctionCallException('not support: redis');
        }
        if (!(self::$_instance instanceof \Redis)) {
            if (!empty($config)) {
                self::$config = array_merge(self::$config, $config);
            }

            $func            = self::$config['persistent'] ? 'pconnect' : 'connect';
            self::$_instance = new \Redis();
            self::$_instance->$func(self::$config['host'], self::$config['port'], self::$config['timeout']);

            if ('' != self::$config['password']) {
                self::$_instance->auth(self::$config['password']);
            }

            if (0 != self::$config['select']) {
                self::$_instance->select(self::$config['select']);
            }
        }
        return self::$_instance;
    }

}